var config = require("./config.js");
var crypto = require("@/utils/encrypt/requestAes/myAesCrypto.js");

// 是否开启ASE加密
var encryptStatus = false;
// 请求时间
var requestTimeout = 500000;

const baseUrl = config.default.baseUrl;

// 拦截返回值
function requestStop(data) {
    // 拦截token过期
    if (data.code == 401) {
        uni.showToast({
            title: data.errMsg,
            icon: "none",
            duration: 2000,
        });
        setTimeout(function() {
            uni.reLaunch({
                url: "/pages/login/login",
            });
        }, 1000);

        return false;
    }

    // 监听非200并返回
    if (data.code != 200 && data.code != 409) {
        uni.showToast({
            title: data.errMsg,
            icon: "none",
            duration: 2500,
        });
    }

    return true;
}

// post请求封装 可以传入methodType类型PUT
function autoRequest(url, data, methodType = "POST", isToken = true) {
    var promise = new Promise((resolve, reject) => {
        uni.request({
            url: baseUrl + url,
            data: encryptStatus ? crypto.aes.en(JSON.stringify(data)) : data,
            method: methodType,
            timeout: requestTimeout,
            // method: 'POST',
            dataType: "json",
            header: {
                // 'content-type': 'application/x-www-form-urlencoded',
                // 'content-type': 'application/json',
                // 'content-type': 'application/text',
                Authorization: isToken ? "Bearer " + uni.getStorageSync("token") : "",
            },
            success: function(res) {
                console.log('success');
                if (res) {
                    if (res.header.token) {
                        var userInfos = uni.getStorageSync("userInfos");
                        userInfos.token = res.header.token;
                        uni.setStorageSync("userInfos", userInfos);
                    }
                    switch (res.statusCode) {
                        case 404:
                            resolve("404，请求的资源不存在");
                            break;
                        case 500:
                            resolve("500，内部服务器错误");
                            break;
                        default:
                            // requestStop(res.data)
                            if (requestStop(res.data)) resolve(res.data);
                    }
                }
            },
            fail: function(e) {
                reject("网络错误！");

                console.log(e, "网络错误");

                uni.showToast({
                    title: "网络错误",
                    // title: e.errMsg,
                    icon: "none",
                });
            },
            complete: (complete) => {
                console.log('打印***complete 完成接收', complete)
            }
        });
    });
    return promise;
}

// get请求封装
function getRequest(url, data, isToken = true) {
    var promise = new Promise((resolve, reject) => {
        var postData = data;
        uni.request({
            url: baseUrl + url,
            data: postData,
            method: "GET",
            timeout: requestTimeout,
            header: {
                // 'content-type': 'application/json',
                Authorization: isToken ? "Bearer " + uni.getStorageSync("token") : "",
            },
            success: function(res) {
                if (res) {
                    if (res.header.token) {
                        var userInfos = uni.getStorageSync("userInfos");
                        userInfos.token = res.header.token;
                        uni.setStorageSync("userInfos", userInfos);
                    }
                    switch (res.statusCode) {
                        case 404:
                            resolve("404，请求的资源不存在");
                            break;
                        case 500:
                            resolve("500，内部服务器错误");
                            break;
                        default:
                            if (requestStop(res.data)) resolve(res.data);
                    }
                }
            },
            fail: function(e) {
                reject("网络错误！");

                console.log(e, "网络错误");

                uni.showToast({
                    title: e.errMsg,
                    icon: "none",
                });
            },
        });
    });
    return promise;
}

function decode(data) {
    console.log('decode', data);
    const text = this.decodeUTF8(data);
    const lines = text.split("\n");
    let result = "";

    for (let line of lines) {
        if (line.startsWith("data: ")) {
            const jsonData = line.slice(6).trim();

            // 结束标识处理
            if (jsonData === "[DONE]") return result;

            // 清理控制字符（防止JSON解析失败）
            const cleanedData = jsonData.replace(/[\u0000-\u001F\u007F-\u009F]/g, "");

            try {
                const parsedData = JSON.parse(cleanedData);
                // 提取AI生成内容
                result += parsedData.choices[0].delta.content || "";
            } catch (e) {
                console.error("解析失败:", e);
            }
        }
    }
    return result;
}
// 流式请求封装
function taskRequest(url, data, isToken = true) {
    // var promise = new Promise((resolve, reject) => {
    const requestTask = uni.request({
        url: baseUrl + url,
        data: encryptStatus ? crypto.aes.en(JSON.stringify(data)) : data,
        timeout: requestTimeout,
        method: "POST",
        // dataType: 'json',
        enableChunked: true,
        responseType: "arraybuffer",
        header: {
            ContentType: 'text/event-stream;charset=utf-8',
            Accept: "text/event-stream;charset=utf-8",
            Authorization: isToken ? "Bearer " + uni.getStorageSync("token") : "",
        },
        success: function(res) {
            if (res) {
                console.log(res);
                if (res.header.token) {
                    var userInfos = uni.getStorageSync("userInfos");
                    userInfos.token = res.header.token;
                    uni.setStorageSync("userInfos", userInfos);
                }
                // switch (res.statusCode) {
                //     case 404:
                //         resolve("404，请求的资源不存在");
                //         break;
                //     case 500:
                //         resolve("500，内部服务器错误");
                //         break;
                //     default:
                //         // requestStop(res.data)
                //         if (requestStop(res.data)) resolve(res.data);
                // }
            }
        },
        // 注册分块接收监听器
        onChunkReceived: (res) => {
            console.log(res.data);
            const decodedData = decode(res.data);
            if (decodedData) {
                onData(decodedData); // 触发数据回调
            }
        },
        fail: function(e) {
            reject("网络错误！");

            console.log(e, "网络错误");

            uni.showToast({
                title: "网络错误",
                // title: e.errMsg,
                icon: "none",
            });
        },
    });
    return requestTask;
    // });
}

module.exports = {
    autoRequest,
    getRequest,
    taskRequest,
};